<template>
  <div class="app-container">
    <el-row :gutter="0">
      <!-- 台账类型菜单 -->
      <el-col :xs="24" :sm="24" :md="3" style="padding:0;margin-right:0;">
        <el-card shadow="never">
          <div
            style="font-weight:bold; margin-bottom:10px; display: flex; align-items: center; justify-content: space-between;">
            <span>台账类型</span>
            <i class="el-icon-plus type-add-icon" @click="showAddTypeDialog = true" style="cursor:pointer;"></i>
          </div>
          <el-menu :default-active="activeType" @select="handleTypeSelect">
            <el-menu-item v-for="type in ledgerTypes" :key="type.value" :index="type.value" class="custom-menu-item">
              <div class="item-icon">
                <i :class="type.icon"></i>
              </div>
              <el-tooltip class="item-title-tooltip" effect="dark" :content="type.label" placement="top"
                :disabled="!isTextTruncated(type.label)">
                <span class="item-title">
                  {{ type.label }}
                </span>
              </el-tooltip>
              <i class="type-delete-icon el-icon-delete" @click.stop="handleDeleteType(type)"></i>
            </el-menu-item>
            <div v-if="ledgerTypes.length === 0" style="padding: 20px; text-align: center; color: #909399;">
              <i class="el-icon-folder-opened" style="font-size: 24px; margin-bottom: 8px;"></i>
              <div>暂无台账类型</div>
              <div style="font-size: 12px; margin-top: 4px;">点击上方"+"添加台账类型</div>
            </div>
          </el-menu>
        </el-card>
      </el-col>
      <!-- 主内容 -->
      <el-col :xs="24" :sm="24" :md="21" style="padding-left:0;margin-left:0;">
        <el-card shadow="never" class="main-card">
          <!-- 查询表单 -->
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="80px">
            <el-form-item label="审核状态" prop="auditStatus">
              <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable filterable>
                <el-option v-for="dict in dict.type.review_status" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="所属项目" prop="projectId">
              <el-select clearable filterable v-model="queryParams.projectId" placeholder="请选择项目">
                <el-option v-for="item in projectOptions" :key="item.id" :label="item.projectName" :value="item.id" />
              </el-select>
            </el-form-item> -->

            <!-- <el-form-item label="规格型号" prop="specificationModel">
              <el-input v-model="queryParams.specificationModel" placeholder="请输入规格型号" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="数量" prop="quantity">
              <el-input v-model="queryParams.quantity" placeholder="请输入数量" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="计量单位" prop="measurementUnit">
              <el-input v-model="queryParams.measurementUnit" placeholder="请输入计量单位" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                v-hasPermi="['cost:warehouseOtherCost:add']">新增</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
              <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                v-hasPermi="['cost:warehouseOtherCost:edit']">修改</el-button>
            </el-col> -->
            <!-- <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                v-hasPermi="['cost:warehouseOtherCost:remove']">删除</el-button>
            </el-col> -->
            <el-col :span="1.5">
              <el-button type="success" icon="el-icon-upload2" size="mini" @click="handleImport"
                v-hasPermi="['cost:warehouseOtherCost:add']">导入</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
                v-hasPermi="['cost:warehouseOtherCost:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>

          <!-- 颜色说明（按 materialLedger 风格） -->
          <!-- <div class="color-legend" style="margin-bottom: 10px; font-size: 12px; color: #666;">
            <span style="margin-right: 15px;">
              <span
                style="display: inline-block; width: 16px; height: 16px; background-color: #fff3cd; border: 1px solid #ddd; margin-right: 5px;"></span>
              黄色：录入时间与截至日期相差超过3天且未审核
            </span>
            <span>
              <span
                style="display: inline-block; width: 16px; height: 16px; background-color: #f8d7da; border: 1px solid #ddd; margin-right: 5px;"></span>
              红色：录入时间与截至日期相差超过7天且未审核
            </span>
          </div> -->

          <el-table v-loading="loading" :data="machineLedgerEntryList" @selection-change="handleSelectionChange"
            :row-class-name="rowClassName">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="日期" width="120" align="center" prop="recordDate">
              <template slot-scope="scope">
                <span>{{ scope.row.recordDate && scope.row.recordDate.length > 9 ? scope.row.recordDate.substr(0, 10) :
                  scope.row.recordDate }}</span>
              </template>
            </el-table-column>
            <el-table-column label="名称" align="center" prop="recordName" />
            <el-table-column label="对方公司" align="center" prop="partnerCompany" />
            <el-table-column label="金额" align="center" prop="amount" />
            <el-table-column label="备注" width="170" align="center" prop="remark" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" :content="scope.row.remark || ''" placement="top"
                  :disabled="!scope.row.remark">
                  <span
                    style="max-width: 100%; display: inline-block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: middle; width: 100%;"
                    :title="scope.row.remark || ''">
                    {{ scope.row.remark || '--' }}
                  </span>
                </el-tooltip>
              </template>
            </el-table-column>
            <!-- <el-table-column label="增值税" align="center" prop="valueAddedTax" /> -->
            <!-- <el-table-column label="录入时间" align="center" prop="entryTime" width="180">
              <template slot-scope="scope">
                <span>{{ scope.row.entryTime && scope.row.entryTime.length > 9 ? scope.row.entryTime.substr(0, 10) :
                  scope.row.entryTime }}</span>
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
            <el-table-column label="审核状态" width="90" align="center" prop="auditStatus">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.review_status" :value="scope.row.auditStatus" />
              </template>
            </el-table-column>
            <!-- <el-table-column label="所属项目" width="160" align="center" prop="projectId">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" :content="getProjectNameById(scope.row.projectId)"
                  placement="top">
                  <span
                    style="max-width: 120px; display: inline-block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: middle;"
                    :title="getProjectNameById(scope.row.projectId)">
                    {{ getProjectNameById(scope.row.projectId) }}
                  </span>
                </el-tooltip>
              </template>
            </el-table-column> -->
            <el-table-column label="操作" width="200" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <!-- 审核按钮 -->
                <el-button v-if="scope.row.auditStatus == 1" v-hasPermi="['cost:warehouseOtherCost:audit']" size="mini"
                  type="text" icon="el-icon-check" @click="handleAudit(scope.row)">审核</el-button>

                <!-- 取消审核按钮 -->
                <el-button v-else-if="scope.row.auditStatus == 2" v-hasPermi="['cost:warehouseOtherCost:unaudit']"
                  size="mini" type="text" icon="el-icon-close" @click="handleCancelAudit(scope.row)">取消审核</el-button>

                <!-- 修改按钮 -->
                <el-button v-if="scope.row.auditStatus == 1" v-hasPermi="['cost:warehouseOtherCost:edit']" size="mini"
                  type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>

                <!-- 详情按钮 -->
                <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>

                <!-- 删除按钮 -->
                <el-button v-if="scope.row.auditStatus == 1" v-hasPermi="['cost:warehouseOtherCost:remove']" size="mini"
                  type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改机械台账对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <!-- 项目总金额显示区域 -->
      <div class="amount-display-section">
        <div class="amount-display-label">当前类型仓库总支出金额：</div>
        <div class="amount-display-content">
          <span v-if="loadingAmount" class="amount-loading">
            <i class="el-icon-loading"></i> 正在获取...
          </span>
          <span v-else class="amount-value">{{ form.projectAmountTotal !== null && form.projectAmountTotal !== undefined
            ?
            form.projectAmountTotal : '选择项目后自动显示' }}</span>
          <span v-if="!loadingAmount && form.projectAmountTotal !== null && form.projectAmountTotal !== undefined"
            class="amount-unit">元</span>
        </div>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="所属项目" prop="projectId">
              <el-input :value="getProjectNameById(19)" disabled />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="审核状态">
              <el-radio-group v-model="form.auditStatus">
                <el-radio v-for="dict in dict.type.review_status" :key="dict.value" :label="parseInt(dict.value)">{{
                  dict.label
                  }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="名称" prop="recordName">
              <el-input v-model="form.recordName" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="日期" prop="recordDate">
              <el-date-picker clearable v-model="form.recordDate" type="date" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择日期" style="width: 100%"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="对方公司" prop="partnerCompany">
              <el-input v-model="form.partnerCompany" placeholder="请输入对方公司" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入金额" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="不含税成本" prop="taxExcludedCost">
              <el-input v-model="form.taxExcludedCost" placeholder="请输入不含税成本" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="增值税" prop="valueAddedTax">
              <el-input v-model="form.valueAddedTax" placeholder="请输入增值税" />
            </el-form-item>
          </el-col>
        </el-row> -->

        <el-row :gutter="20">
          <!-- <el-col :span="12">
            <el-form-item label="审核状态" prop="auditStatus">
              <el-radio-group v-model="form.auditStatus">
                <el-radio v-for="dict in dict.type.review_status" :key="dict.value" :label="parseInt(dict.value)">{{
                  dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="12">
            <el-form-item label="所属项目" prop="projectId">
              <el-select v-model="form.projectId" placeholder="请选择项目" style="width: 100%">
                <el-option v-for="item in projectOptions" :key="item.id" :label="item.projectName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col> -->

          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <!-- <el-col :span="12">
            <el-form-item label="录入时间" prop="entryTime">
              <el-date-picker clearable v-model="form.entryTime" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择录入时间" style="width: 100%"></el-date-picker>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :rows="3" />
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-form-item label="上传凭证" class="upload-form-item">
          <div class="upload-container">
            <el-upload ref="upload" drag action="#" :auto-upload="true" list-type="picture-card"
              :on-change="onUploadChange" :on-remove="onUploadRemove" :on-exceed="onUploadExceed"
              :file-list="uploadFileList" accept="image/*" class="upload-component" :http-request="handleCustomUpload">
              <i class="el-icon-upload" />
              <div class="el-upload__text">
                将图片拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                仅用于随单据上传的图片凭证，支持多张
              </div>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="上传文件" class="upload-form-item">
          <div class="upload-container">
            <el-upload ref="fileUpload" drag action="#" :auto-upload="true" list-type="text"
              :on-change="onFileUploadChange" :on-remove="onFileUploadRemove" :on-exceed="onFileUploadExceed"
              :file-list="uploadDocumentList" accept=".pdf,.doc,.docx" class="file-upload-component"
              :http-request="handleFileCustomUpload">
              <i class="el-icon-upload" />
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                仅支持PDF和Word文件，支持多个文件
              </div>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加台账类型对话框 -->
    <el-dialog title="添加台账类型" :visible.sync="showAddTypeDialog" width="500px" append-to-body
      @close="addTypeForm.typeName = ''">
      <el-form :model="addTypeForm" @submit.native.prevent>
        <el-form-item label="类型名称" label-width="80px">
          <el-input v-model="addTypeForm.typeName" placeholder="请输入类型名称" @keyup.enter.native.prevent />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddTypeDialog = false">取 消</el-button>
        <el-button type="primary" :loading="addTypeLoading" @click="handleAddType">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog :visible.sync="detailOpen" width="900px" :show-close="true" append-to-body class="daily-detail-dialog">
      <div class="daily-detail-title">机械台账详情</div>

      <div class="daily-section-title">基本信息</div>
      <div class="daily-row-flex">
        <div class="daily-col-flex">
          <table class="daily-detail-table">
            <tr>
              <th class="left-align">名称</th>
              <td class="value">{{ detailForm.recordName }}</td>
            </tr>
            <tr>
              <th class="left-align">日期</th>
              <td class="value">{{ detailForm.recordDate && detailForm.recordDate.length > 9 ?
                detailForm.recordDate.substr(0, 10) : detailForm.recordDate }}</td>
            </tr>
            <tr>
              <th class="left-align">对方公司</th>
              <td class="value">{{ detailForm.partnerCompany }}</td>
            </tr>
            <tr>
              <th class="left-align">金额</th>
              <td class="value">{{ detailForm.amount }}</td>
            </tr>

          </table>
        </div>
        <div class="daily-col-flex">
          <table class="daily-detail-table">
            <tr>
              <th class="left-align">所属项目</th>
              <td class="value">{{ getProjectNameById(detailForm.projectId) }}</td>
            </tr>
            <tr>
              <th class="left-align">审核状态</th>
              <td class="value"><dict-tag :options="dict.type.review_status" :value="detailForm.auditStatus" /></td>
            </tr>
            <tr>
              <th class="left-align">备注</th>
              <td class="value">{{ detailForm.remark }}</td>
            </tr>
          </table>
        </div>
      </div>
      <!-- 图片展示区域 -->
      <div class="daily-section-title">凭证信息</div>
      <div v-if="detailImageUrls && detailImageUrls.length > 0" class="image-display-container">
        <div v-for="(url, index) in detailImageUrls" :key="`display-${index}`" class="image-item">
          <el-image :src="url" :preview-src-list="detailImageUrls" fit="cover" class="detail-image">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </div>
      </div>

      <!-- 文件展示区域 -->
      <div v-if="detailFileList && detailFileList.length > 0" class="daily-section-title">附件信息</div>
      <div v-if="detailFileList && detailFileList.length > 0" class="file-display-container">
        <div v-for="(file, index) in detailFileList" :key="`file-${index}`" class="file-item">
          <div class="file-info">
            <i class="el-icon-document"></i>
            <span class="file-name">{{ file.fileName }}</span>
            <div class="file-actions">
              <el-button type="primary" size="mini" icon="el-icon-download" @click="handleFileDownload(file)">
                下载
              </el-button>
              <el-button type="success" size="mini" icon="el-icon-view" @click="handleFilePreview(file)">
                预览
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false" type="primary" plain>关闭</el-button>
      </span>
    </el-dialog>

    <!-- 导入弹窗 -->
    <el-dialog title="导入机械台账填报" :visible.sync="importOpen" width="500px" append-to-body>
      <el-form ref="importForm" :model="importForm" :rules="importRules" label-width="100px">
        <el-form-item label="所属项目" prop="porjectId">
          <el-select v-model="importForm.porjectId" placeholder="请选择所属项目" style="width: 100%" :disabled="true">
            <el-option v-for="item in projectOptions" :key="item.id" :label="item.projectName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择文件" prop="file">
          <el-upload ref="upload" :limit="1" accept=".xlsx,.xls" :headers="upload.headers" :action="upload.url"
            :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
            :on-change="handleFileChange" :auto-upload="false" drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link type="primary" :underline="false"
                style="font-size:12px;vertical-align: baseline; margin-left: 8px;"
                @click="importTemplate">下载模板</el-link>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImport" :loading="upload.isUploading">确 定</el-button>
        <el-button @click="cancelImport">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 文件预览弹框 -->
    <el-dialog :visible.sync="previewDialogVisible" width="60vw" top="5vh" :title="getPreviewTitle()"
      @close="previewFile = null">
      <div v-if="previewFile">
        <!-- 图片预览 -->
        <el-image v-if="getFileType(previewFile.fileName) === 'image'" :src="previewFile.downloadUrl"
          :preview-src-list="[previewFile.downloadUrl]" fit="contain"
          style="max-width:100%;max-height:70vh;display:block;margin:auto;cursor:pointer;">
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
          </div>
        </el-image>
        <!-- 文档/PDF/Word/Excel 预览：直接用iframe打开 -->
        <iframe v-else-if="['pdf', 'word', 'excel', 'ppt'].includes(getFileType(previewFile.fileName))"
          :src="previewFile.downloadUrl" style="width:100%;height:70vh;border:none;"></iframe>
        <!-- 其他类型提示 -->
        <div v-else style="text-align:center;padding:40px 0;color:#888;">
          暂不支持该类型文件的在线预览，请下载后查看。
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { prodProjectLaborFileImport, } from "@/api/cost/prodProjectLabor";
import { listMaterialLedgerType, addMaterialLedgerType, delMaterialLedgerType } from "@/api/cost/materialLedgerType";
import { listAllProjectContractInfo } from '@/api/production/projectContractInfo';
import { addImg, delImg } from "@/api/cost/materialLedger";
import { fileLinkTransfer, fileLinkLooking } from "@/api/production/projectFileInfo";
import { addWarehouseOtherCost, updateWarehouseOtherCost, getWarehouseOtherCost, listWarehouseOtherCost, delWarehouseOtherCost, getAmountTotal } from "@/api/cost/warehouseOtherCost";

export default {
  name: "warehouseOtherCost",
  dicts: ['review_status', 'input_tax'],
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      machineLedgerEntryList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        auditStatus: null,
        startTime: null,
        endTime: null,
        specificationModel: null,
        quantity: null,
        measurementUnit: null,
        taxIncludedUnitPrice: null,
        amount: null,
        shippingFee: null,
        supplier: null,
        inputTaxRate: null,
        taxExcludedCost: null,
        valueAddedTax: null,
        entryTime: null,
        remark: null,
        projectId: 19,
        accountTypeId: null, // 新增：台账类型ID
      },
      form: {
        fileList: [], // 存储转换后的文件链接数组
        projectAmountTotal: null, // 项目总含税金额
      },
      // 加载状态
      loadingAmount: false,
      rules: {
        recordName: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        id: [
          { required: true, message: "主键ID不能为空", trigger: "blur" }
        ],
        recordDate: [
          { required: true, message: "日期不能为空", trigger: "blur" }
        ],
        partnerCompany: [
          { required: true, message: "对方公司不能为空", trigger: "blur" }
        ],
        amount: [
          { required: true, message: "金额不能为空", trigger: "blur" }
        ],
        // remark: [
        //   { required: true, message: "备注不能为空", trigger: "blur" }
        // ],
        projectId: [
          { required: true, message: "所属项目id不能为空", trigger: "blur" }
        ],
        accountTypeId: [
          { required: true, message: "台账类型不能为空", trigger: "change" }
        ],
      },
      projectOptions: [],
      ledgerTypes: [],
      activeType: '',
      showAddTypeDialog: false,
      addTypeForm: { typeName: '' },
      addTypeLoading: false,
      typeParams: {
        pageNum: 1,
        pageSize: 10,
        typeName: null,
        remark: null
      },
      detailOpen: false,
      detailForm: {},
      // 详情页面的图片链接
      detailImageUrls: [],
      // 详情页面的文件列表
      detailFileList: [],
      // 文件预览相关
      previewDialogVisible: false,
      previewFile: null,
      // 处理后的图片链接（用于回显）
      processedImageList: [],
      // 上传文件列表（图片）
      uploadFileList: [],
      // 上传文件列表（文档）
      uploadDocumentList: [],
      // 导入相关
      importOpen: false,
      importForm: { porjectId: 19, file: null },
      importRules: {
        porjectId: [{ required: true, message: "请选择所属项目", trigger: "change" }],
        file: [{ required: true, message: "请选择要导入的文件", trigger: "change" }]
      },
      upload: {
        isUploading: false,
        headers: {},
        url: process.env.VUE_APP_BASE_API + "/common/upload"
      }
    };
  },
  created() {
    this.fetchProjectOptions();
    this.getTypeList();
    // 设置上传请求头
    this.upload.headers = { Authorization: "Bearer " + this.$store.getters.token };
    // this.getList(); // 移除多余的请求，避免重复
  },
  methods: {
    /**
     * 计算表格行样式：录入时间(entryTime) - 截止时间(endTime)
     * 间隔大于3天标黄，大于7天标红
     */
    rowClassName({ row }) {
      // 仅未审核时显示颜色（未审核: 1）
      if (row.auditStatus != 1) return '';
      const entry = this.parseDate(row.entryTime);
      const end = this.parseDate(row.endTime);
      if (!entry || !end) return '';
      const diffDays = Math.floor((entry.getTime() - end.getTime()) / 86400000);
      if (diffDays > 7) return 'over-seven-days';
      if (diffDays > 3) return 'over-three-days';
      return '';
    },
    // 兼容多种日期字符串格式的解析
    parseDate(val) {
      if (!val) return null;
      if (val instanceof Date) return isNaN(val.getTime()) ? null : val;
      if (typeof val === 'string') {
        let s = val.trim();
        // 统一分隔符并兼容带时间的字符串
        s = s.replace('T', ' ').replace(/-/g, '/');
        const d = new Date(s);
        if (!isNaN(d.getTime())) return d;
        // 退化为仅日期部分
        const onlyDate = s.slice(0, 10);
        const d2 = new Date(onlyDate);
        return isNaN(d2.getTime()) ? null : d2;
      }
      return null;
    },
    getList() {
      this.loading = true;
      // 固定查询项目为ID 19
      this.queryParams.projectId = 19;
      listWarehouseOtherCost(this.queryParams).then(response => {
        this.machineLedgerEntryList = response.rows || [];
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        auditStatus: null,
        recordName: null,
        recordDate: null,
        partnerCompany: null,
        amount: null,
        remark: null,
        projectId: null,
        accountTypeId: null, // 新增：台账类型ID
        fileList: [], // 重置文件链接数组
      };
      this.uploadFileList = [];
      this.uploadDocumentList = []; // 重置文档上传列表
      this.processedImageList = []; // 重置处理后的图片链接
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      // 保持固定项目为ID 19
      this.queryParams.projectId = 19;
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      if (!this.activeType) {
        this.$message.warning('请先选择劳务类型');
        return;
      }
      this.reset();
      this.form.auditStatus = 1; // 新增时默认未审核
      // 固定项目为ID 19并刷新金额显示
      this.form.projectId = 19;
      this.handleProjectChange(19);
      this.open = true;
      this.title = "添加机械台账填报";
    },
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      try {
        const response = await getWarehouseOtherCost(id);
        this.form = response.data;

        // 固定项目为ID 19并刷新金额显示
        this.form.projectId = 19;
        this.handleProjectChange(19);

        // 处理图片回显
        await this.processImageListForDisplay();

        this.open = true;
        this.title = "修改机械台账填报";
      } catch (error) {
        console.error("修改 - 获取数据失败:", error);
        this.$message.error("获取数据失败");
      }
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 添加时带上当前选中的台账类型id
          if (!this.form.id) {
            this.form.accountTypeId = this.activeType;
          }
          // 提交前固定项目为ID 19
          this.form.projectId = 19;
          if (this.form.id != null) {
            updateWarehouseOtherCost(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.auditStatus = 1; // 新增时默认未审核
            addWarehouseOtherCost(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除？').then(function () {
        return delWarehouseOtherCost(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    handleExport() {
      this.download('cost/warehouseOtherCost/export', {
        ...this.queryParams
      }, `machineLedgerEntry_${new Date().getTime()}.xlsx`)
    },
    fetchProjectOptions() {
      listAllProjectContractInfo().then(res => {
        this.projectOptions = res.data || [];
        // console.log('项目列表:', this.projectOptions);
      });
    },
    getProjectNameById(projectId) {
      const item = this.projectOptions.find(p => p.id == projectId);
      return String(item ? item.projectName : (projectId ?? ''));
    },
    /** 处理项目选择变化 */
    async handleProjectChange(projectId) {
      // 先清空当前值，避免显示上一次的结果
      this.form.projectAmountTotal = null;

      if (!projectId || !this.activeType) {
        return;
      }

      // 显示加载状态
      this.loadingAmount = true;

      try {
        const response = await getAmountTotal(this.activeType, projectId);
        this.form.projectAmountTotal = response.data || 0;
      } catch (error) {
        console.error("获取项目总含税金额失败:", error);
        this.$message.error("获取项目总含税金额失败");
        this.form.projectAmountTotal = null;
      } finally {
        // 无论成功失败都要关闭加载状态
        this.loadingAmount = false;
      }
    },
    /** 查询台账类型列表 */
    getTypeList() {
      const params = {
        ...this.typeParams,
        menuType: 'warehouseCostPage'
      };
      listMaterialLedgerType(params).then(response => {
        this.ledgerTypes = [];
        response.rows.forEach(item => {
          this.ledgerTypes.push({
            label: item.typeName,
            value: String(item.id),
            icon: 'el-icon-document'
          });
        });
        if (this.ledgerTypes.length > 0) {
          this.activeType = this.ledgerTypes[0].value;
          this.queryParams.accountTypeId = this.ledgerTypes[0].value;
        } else {
          this.activeType = '';
          this.queryParams.accountTypeId = null;
        }
        this.getList();
      }).catch(error => {
        this.ledgerTypes = [];
        this.activeType = '';
        this.queryParams.accountTypeId = null;
        this.getList();
      });
    },
    handleTypeSelect(val) {
      this.activeType = String(val);
      this.queryParams.accountTypeId = String(val);
      this.form.accountTypeId = String(val);
      this.getList();
    },
    handleDeleteType(type) {
      // 先检查该台账类型下是否有数据
      const checkParams = {
        pageNum: 1,
        pageSize: 1,
        accountTypeId: type.value,
        projectId: 19
      };

      listWarehouseOtherCost(checkParams).then(response => {
        const hasData = response.total && response.total > 0;
        if (hasData) {
          this.$message.warning('该类型下有台账数据，不能删除！');
          return;
        }

        // 没有数据，可以删除
        this.$confirm(`是否确认删除台账类型"${type.label}"？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delMaterialLedgerType(type.value).then(() => {
            this.$message.success('删除成功');
            this.getTypeList();
          });
        }).catch(() => { });
      }).catch(error => {
        console.error('检查台账类型数据失败:', error);
        this.$message.error('检查台账类型数据失败，请稍后再试');
      });
    },
    handleAddType() {
      if (!this.addTypeForm.typeName.trim()) {
        this.$message.warning('请输入类型名称');
        return;
      }
      this.addTypeLoading = true;
      addMaterialLedgerType({
        typeName: this.addTypeForm.typeName,
        menuType: 'warehouseCostPage'
      }).then(() => {
        this.$message.success('添加成功');
        this.showAddTypeDialog = false;
        this.addTypeForm.typeName = '';
        this.getTypeList();
      }).finally(() => {
        this.addTypeLoading = false;
      });
    },
    // 检测文本是否被截断
    isTextTruncated(text) {
      if (!text) return false;

      // 创建临时元素来测量文本实际宽度
      const tempElement = document.createElement('span');
      tempElement.style.cssText = `
        position: absolute;
        visibility: hidden;
        white-space: nowrap;
        font-size: 14px;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
        width: auto;
        height: auto;
      `;
      tempElement.textContent = text;
      document.body.appendChild(tempElement);

      const textWidth = tempElement.offsetWidth;
      const containerWidth = 120; // 容器宽度

      document.body.removeChild(tempElement);

      return textWidth > containerWidth;
    },
    async handleDetail(row) {
      try {
        const response = await getWarehouseOtherCost(row.id);
        this.detailForm = response.data;

        // 处理图片和文件链接转换
        await this.processDetailImageAndFiles();

        this.detailOpen = true;
      } catch (error) {
        console.error("获取详情失败:", error);
        this.$message.error("获取详情失败");
      }
    },
    handleAudit(row) {
      const data = { ...row, auditStatus: 2, clickAudit: true };
      updateWarehouseOtherCost(data).then(() => {
        this.$modal.msgSuccess('审核成功');
        this.getList();
      });
    },
    handleCancelAudit(row) {
      const data = { ...row, auditStatus: 1, clickAudit: true };
      updateWarehouseOtherCost(data).then(() => {
        this.$modal.msgSuccess('已取消审核');
        this.getList();
      });
    },
    // 导入：打开/取消/重置
    handleImport() {
      if (!this.activeType) {
        this.$message.warning('请先选择劳务类型');
        return;
      }
      this.importOpen = true;
      this.resetImport();
    },
    cancelImport() {
      this.importOpen = false;
      this.resetImport();
    },
    resetImport() {
      this.importForm = { porjectId: 19, file: null };
      if (this.$refs.upload) this.$refs.upload.clearFiles();
      this.resetForm('importForm');
    },
    handleFileUploadProgress() {
      this.upload.isUploading = true;
    },
    handleFileSuccess(response, file) {
      this.upload.isUploading = false;
      this.importForm.file = file;
    },
    handleFileChange(file) {
      this.importForm.file = file;
    },
    submitImport() {
      this.$refs['importForm'].validate(valid => {
        if (!valid) return;
        if (!this.importForm.file && (!this.$refs.upload || !this.$refs.upload.uploadFiles.length)) {
          this.$modal.msgError('请选择要导入的文件');
          return;
        }
        const file = this.importForm.file || (this.$refs.upload ? this.$refs.upload.uploadFiles[0] : null);
        if (!file) {
          this.$modal.msgError('请选择要导入的文件');
          return;
        }
        this.upload.isUploading = true;
        prodProjectLaborFileImport(file, this.importForm.porjectId).then(() => {
          this.$modal.msgSuccess('导入成功');
          this.importOpen = false;
          this.resetImport();
          this.getList();
        }).catch(() => {
          this.upload.isUploading = false;
        });
      });
    },
    importTemplate() {
      const url = 'https://ggkt-1319488159.cos.ap-beijing.myqcloud.com/%E6%88%90%E6%9C%AC%E7%AE%A1%E7%90%86%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88/%E9%A1%B9%E7%9B%AE%E5%8A%B3%E5%8A%A1%E5%8F%B0%E8%B4%A6%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx';
      window.open(url, '_blank');
    },
    // 处理详情页面的图片和文件
    async processDetailImageAndFiles() {
      if (!this.detailForm.fileList?.length) {
        this.detailImageUrls = [];
        this.detailFileList = [];
        return;
      }

      this.detailImageUrls = [];
      this.detailFileList = [];

      for (let i = 0; i < this.detailForm.fileList.length; i++) {
        const url = this.detailForm.fileList[i];
        try {
          const displayUrl = await this.getDisplayImageUrl(url);
          const fileName = this.getFileNameFromUrl(url);
          const fileType = this.getFileType(fileName);

          if (this.isImageFile(fileType)) {
            // 图片文件
            this.detailImageUrls.push(displayUrl);
          } else {
            // 文档文件
            this.detailFileList.push({
              fileName: fileName,
              downloadUrl: url,
              displayUrl: displayUrl,
              fileType: fileType
            });
          }
        } catch (error) {
          console.error(`处理文件失败:`, error);
        }
      }
    },
    // 获取文件类型
    getFileType(fileName) {
      if (!fileName) return 'unknown';
      const extension = fileName.split('.').pop().toLowerCase();
      const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
      const pdfTypes = ['pdf'];
      const wordTypes = ['doc', 'docx'];
      const excelTypes = ['xls', 'xlsx'];
      const pptTypes = ['ppt', 'pptx'];

      if (imageTypes.includes(extension)) return 'image';
      if (pdfTypes.includes(extension)) return 'pdf';
      if (wordTypes.includes(extension)) return 'word';
      if (excelTypes.includes(extension)) return 'excel';
      if (pptTypes.includes(extension)) return 'ppt';
      return 'unknown';
    },
    // 判断是否为图片文件
    isImageFile(fileType) {
      return fileType === 'image';
    },
    // 从URL中提取文件名
    getFileNameFromUrl(url) {
      if (!url) return 'unknown';
      const parts = url.split('/');
      return parts[parts.length - 1] || 'unknown';
    },
    // 文件下载
    async handleFileDownload(file) {
      if (!file.downloadUrl) {
        this.$message.error("无效的下载链接");
        return;
      }
      try {
        const res = await fileLinkTransfer(file.downloadUrl);
        const newUrl = res.data.url;
        if (!newUrl) {
          this.$message.error("获取下载链接失败");
          return;
        }
        // 创建a标签下载
        const a = document.createElement("a");
        a.href = newUrl;
        a.download = file.fileName || "";
        a.target = "_blank";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      } catch (e) {
        this.$message.error("下载失败");
      }
    },
    // 文件预览
    async handleFilePreview(file) {
      if (!file.downloadUrl) {
        this.$message.error("无效的预览链接");
        return;
      }
      try {
        let newUrl = '';
        const fileType = this.getFileType(file.fileName);

        if (fileType === 'image') {
          // 图片直接使用fileLinkTransfer
          const res = await fileLinkTransfer(file.downloadUrl);
          newUrl = res.data.url;
        } else if (['pdf', 'word', 'excel', 'ppt'].includes(fileType)) {
          // 文档使用fileLinkLooking
          const res = await fileLinkLooking(file.downloadUrl);
          newUrl = res.data.url;
        } else {
          newUrl = file.downloadUrl;
        }

        if (!newUrl) {
          this.$message.error("获取预览链接失败");
          return;
        }

        this.previewFile = { ...file, downloadUrl: newUrl };
        this.previewDialogVisible = true;
      } catch (e) {
        this.$message.error("预览失败");
      }
    },
    // 获取预览标题
    getPreviewTitle() {
      if (this.previewFile && this.previewFile.fileName) {
        return this.previewFile.fileName;
      }
      return "文件预览";
    },
    // 上传相关方法
    onUploadChange(file, fileList) {
      this.uploadFileList = fileList;
    },
    // 自定义上传：调用 addImg 接口将文件转为图片链接
    async handleCustomUpload(param) {
      const { file } = param || {};
      if (!file) {
        param?.onError?.(new Error("无可上传文件"));
        return;
      }

      try {
        // 上传文件并获取原始路径
        const { msg: filePath } = await addImg(file);
        if (!filePath) {
          throw new Error("未获取到文件路径");
        }

        // 获取可访问链接
        const {
          data: { url },
        } = await fileLinkTransfer(filePath);
        if (!url) {
          throw new Error("未获取到可访问的图片链接");
        }

        // 创建文件项，保存原始路径用于删除
        const fileItem = {
          name: file.name || "image.jpg",
          url,
          uid: file.uid?.toString() || Date.now().toString(),
          originalPath: filePath, // 保存原始路径
        };

        // 更新文件列表和表单数据
        this.uploadFileList = [...this.uploadFileList, fileItem];
        this.form.fileList.push(filePath);

        // 调用成功回调
        param?.onSuccess?.({ url });
      } catch (err) {
        this.$message.error("图片上传失败");
        param?.onError?.(err);
      }
    },
    // 删除图片：仅本地移除，不调用后端
    async onUploadRemove(file, fileList) {
      const { url } = file || {};
      if (!url) {
        this.uploadFileList = fileList;
        return;
      }

      // 找到对应的文件项，获取原始路径，仅更新本地数组
      const fileItem = this.uploadFileList.find((item) => item.url === url);
      if (fileItem && fileItem.originalPath) {
        const originalPath = fileItem.originalPath;
        const fileListIndex = this.form.fileList.indexOf(originalPath);
        if (fileListIndex > -1) {
          this.form.fileList.splice(fileListIndex, 1);
        }
      }
      this.uploadFileList = fileList;
    },
    onUploadExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${fileList.length} 张图片，已选择 ${files.length} 张`
      );
    },
    // 文件上传相关方法
    onFileUploadChange(file, fileList) {
      this.uploadDocumentList = fileList;
    },
    // 自定义文件上传：调用 addImg 接口将文件转为文件链接
    async handleFileCustomUpload(param) {
      const { file } = param || {};
      if (!file) {
        param?.onError?.(new Error("无可上传文件"));
        return;
      }

      // 检查文件类型
      const allowedTypes = ['.pdf', '.doc', '.docx'];
      const fileExtension = '.' + file.name.split('.').pop().toLowerCase();
      if (!allowedTypes.includes(fileExtension)) {
        this.$message.error("只支持PDF和Word文件");
        param?.onError?.(new Error("文件类型不支持"));
        return;
      }

      try {
        // 上传文件并获取原始路径
        const { msg: filePath } = await addImg(file);
        if (!filePath) {
          throw new Error("未获取到文件路径");
        }

        // 获取可访问链接
        const {
          data: { url },
        } = await fileLinkTransfer(filePath);
        if (!url) {
          throw new Error("未获取到可访问的文件链接");
        }

        // 创建文件项，保存原始路径用于删除
        const fileItem = {
          name: file.name || "document.pdf",
          url,
          uid: file.uid?.toString() || Date.now().toString(),
          originalPath: filePath, // 保存原始路径
        };

        // 更新文件列表和表单数据
        this.uploadDocumentList = [...this.uploadDocumentList, fileItem];
        this.form.fileList.push(filePath);

        // 调用成功回调
        param?.onSuccess?.({ url });
      } catch (err) {
        this.$message.error("文件上传失败");
        param?.onError?.(err);
      }
    },
    // 删除文件：仅本地移除，不调用后端
    async onFileUploadRemove(file, fileList) {
      const { url } = file || {};
      if (!url) {
        this.uploadDocumentList = fileList;
        return;
      }

      // 找到对应的文件项，获取原始路径，仅更新本地数组
      const fileItem = this.uploadDocumentList.find((item) => item.url === url);
      if (fileItem && fileItem.originalPath) {
        const originalPath = fileItem.originalPath;
        const fileListIndex = this.form.fileList.indexOf(originalPath);
        if (fileListIndex > -1) {
          this.form.fileList.splice(fileListIndex, 1);
        }
      }
      this.uploadDocumentList = fileList;
    },
    onFileUploadExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${fileList.length} 个文件，已选择 ${files.length} 个`
      );
    },
    // 获取可访问的图片链接（用于显示）
    async getDisplayImageUrl(url) {
      if (!url) {
        return "";
      }

      try {
        const {
          data: { url: accessibleUrl },
        } = await fileLinkTransfer(url);
        return accessibleUrl || url;
      } catch (error) {
        console.error("getDisplayImageUrl - 转换失败:", error);
        return url;
      }
    },
    // 处理图片列表用于显示
    async processImageListForDisplay() {
      if (!this.form.fileList?.length) {
        this.form.fileList = [];
        this.uploadFileList = [];
        this.uploadDocumentList = [];
        return;
      }

      this.uploadFileList = [];
      this.uploadDocumentList = [];

      for (let i = 0; i < this.form.fileList.length; i++) {
        const url = this.form.fileList[i];
        try {
          const displayUrl = await this.getDisplayImageUrl(url);
          const fileName = this.getFileNameFromUrl(url);
          const fileType = this.getFileType(fileName);

          if (this.isImageFile(fileType)) {
            // 图片文件，添加到图片上传列表，保存原始路径用于删除
            this.uploadFileList.push({
              name: fileName || `image_${i + 1}.jpg`,
              url: displayUrl,
              uid: `existing_image_${i}`,
              originalPath: url, // 保存原始路径（fileList中的路径）
            });
          } else {
            // 文档文件，添加到文件上传列表，保存原始路径用于删除
            this.uploadDocumentList.push({
              name: fileName || `document_${i + 1}`,
              url: displayUrl,
              uid: `existing_file_${i}`,
              originalPath: url, // 保存原始路径（fileList中的路径）
            });
          }
        } catch (error) {
          console.error(`processImageListForDisplay - 转换失败:`, error);
          // 转换失败时，根据文件名判断类型
          const fileName = this.getFileNameFromUrl(url);
          const fileType = this.getFileType(fileName);

          if (this.isImageFile(fileType)) {
            this.uploadFileList.push({
              name: fileName || `image_${i + 1}.jpg`,
              url,
              uid: `existing_image_${i}`,
              originalPath: url, // 保存原始路径（fileList中的路径）
            });
          } else {
            this.uploadDocumentList.push({
              name: fileName || `document_${i + 1}`,
              url,
              uid: `existing_file_${i}`,
              originalPath: url, // 保存原始路径（fileList中的路径）
            });
          }
        }
      }
    },
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  height: calc(100vh - 140px);
  overflow: auto;
  box-sizing: border-box;
  padding-bottom: 24px;
}

//.main-card {
// 可根据 materialLedger 的样式调整
//}

.el-menu {
  border-right: none;
}

.type-delete-icon {
  display: none;
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
}

.el-menu-item:hover .type-delete-icon {
  display: inline-block;
}

.daily-detail-dialog .el-dialog__body {
  background: #f4f6fb;
  padding: 0;
}

.daily-detail-title {
  font-size: 28px;
  font-weight: bold;
  color: #2d3a4b;
  margin-bottom: 36px;
  text-align: center;
  letter-spacing: 2px;
}

.daily-section-title {
  font-size: 18px;
  color: #4a90e2;
  font-weight: bold;
  margin: 32px 0 16px 0;
  border-left: 4px solid #4a90e2;
  padding-left: 12px;
  letter-spacing: 1px;
}

.daily-row-flex {
  display: flex;
  gap: 32px;
  margin-bottom: 12px;
}

.daily-col-flex {
  flex: 1;
}

.daily-detail-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  background: none;
}

.daily-detail-table th,
.daily-detail-table td {
  padding: 10px 8px;
  font-size: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.daily-detail-table th {
  width: 120px;
  color: #6b7a90;
  background: none;
  font-weight: normal;
  text-align: right;
  vertical-align: top;
  padding-right: 12px;
}

.daily-detail-table td.value {
  color: #222;
  text-align: left;
  font-weight: 500;
}

.daily-detail-table tr:last-child td,
.daily-detail-table tr:last-child th {
  border-bottom: none;
}

@media (max-width: 900px) {
  .daily-row-flex {
    flex-direction: column;
    gap: 0;
  }
}

@media (max-width: 600px) {
  .daily-detail-title {
    font-size: 20px;
  }

  .daily-section-title {
    font-size: 15px;
    padding-left: 8px;
  }

  .daily-detail-table th,
  .daily-detail-table td {
    font-size: 13px;
    padding: 7px 4px;
  }
}

/* 行着色：>3天黄色，>7天红色 */
::v-deep .el-table .over-three-days>td {
  background-color: #fff3cd !important;
}

::v-deep .el-table .over-seven-days>td {
  background-color: #f8d7da !important;
}

/* 完全去掉表格鼠标移入的默认hover效果 */
::v-deep .el-table__body tr:hover>td {
  background-color: inherit !important;
}

::v-deep .el-table__body tr:hover {
  background-color: inherit !important;
}

/* 确保自定义的行样式在hover时保持不变 */
::v-deep .el-table__body tr.over-three-days:hover>td {
  background-color: #fff3cd !important;
}

::v-deep .el-table__body tr.over-three-days:hover {
  background-color: #fff3cd !important;
}

::v-deep .el-table__body tr.over-seven-days:hover>td {
  background-color: #f8d7da !important;
}

::v-deep .el-table__body tr.over-seven-days:hover {
  background-color: #f8d7da !important;
}

.el-card {
  padding: 0 !important;
}

::v-deep .el-card__body {
  padding: 8px !important;
}

::v-deep .el-menu {
  padding: 0 !important;
  border-right: none !important;
}

::v-deep .el-menu-item {
  padding-left: 0 !important;
  padding-right: 0 !important;
  width: 100%;
  box-sizing: border-box;
}

/* 同步 materialLedger 的菜单样式 */
.custom-menu-item {
  display: flex !important;
  align-items: center;
  position: relative;
  padding-right: 8px;
}

.item-icon {
  margin-right: 0;
  /* 去除图标与标题间距 */
  flex-shrink: 0;
}

.item-title-tooltip {
  flex: 1 1 120px;
  max-width: 120px;
  min-width: 0;
  margin-right: 8px;
}

.item-title {
  display: inline-block;
  width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

.type-delete-icon {
  color: #F56C6C;
  padding: 0;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.2s;
  margin-left: 8px;
}

.custom-menu-item:hover .type-delete-icon {
  opacity: 1;
}

.amount-value {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
  margin-right: 8px;
}

.amount-unit {
  font-size: 14px;
  color: #666;
}

.amount-loading {
  color: #409EFF;
  font-size: 14px;
}

/* 上传组件样式 */
.upload-container {
  width: 100%;
  overflow: hidden;
  margin-bottom: 10px;
}

.upload-component {
  width: 100%;
}

/* 上传表单项样式 */
.upload-form-item {
  margin-bottom: 20px;
}

.upload-form-item .el-form-item__content {
  margin-bottom: 10px;
}

::v-deep .upload-component .el-upload--picture-card {
  width: 120px;
  height: 120px;
  line-height: 118px;
}

::v-deep .upload-component .el-upload-list--picture-card .el-upload-list__item {
  width: 120px;
  height: 120px;
}

::v-deep .upload-component .el-upload-dragger {
  width: 100%;
  height: 120px;
}

::v-deep .upload-component .el-upload-list--picture-card {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
  margin-bottom: 10px;
}

::v-deep .upload-component .el-upload-list--picture-card .el-upload-list__item {
  margin: 0;
}

/* 确保上传组件在对话框内不会溢出 */
::v-deep .el-dialog__body .upload-container {
  max-width: 100%;
  box-sizing: border-box;
}

/* 统一上传组件样式，避免双重边框 */
::v-deep .upload-component .el-upload-dragger {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
}

::v-deep .upload-component .el-upload-dragger:hover {
  border-color: #409eff;
}

/* 调整对话框底部按钮区域的上边距 */
::v-deep .el-dialog__footer {
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

/* 文件上传组件样式 */
.file-upload-component {
  width: 100%;
}

.file-upload-component .el-upload-dragger {
  width: 100%;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background: #fafafa;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.file-upload-component .el-upload-dragger:hover {
  border-color: #409eff;
}

.file-upload-component .el-upload__text {
  color: #606266;
  font-size: 14px;
  text-align: center;
  margin-top: 8px;
}

.file-upload-component .el-upload__text em {
  color: #409eff;
  font-style: normal;
}

.file-upload-component .el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  text-align: center;
}

/* 文件列表样式 */
.file-upload-component .el-upload-list--text {
  margin-top: 8px;
}

.file-upload-component .el-upload-list--text .el-upload-list__item {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 8px 12px;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.file-upload-component .el-upload-list--text .el-upload-list__item-name {
  color: #606266;
  font-size: 14px;
  flex: 1;
  margin-right: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-upload-component .el-upload-list--text .el-upload-list__item-status-label {
  color: #67c23a;
  font-size: 12px;
}

.file-upload-component .el-upload-list--text .el-upload-list__item-delete {
  color: #f56c6c;
  cursor: pointer;
  font-size: 16px;
}

/* 详情弹窗图片展示样式 */
.image-display-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin: 16px 0;
}

.image-item {
  width: 120px;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
}

.detail-image {
  width: 100%;
  height: 100%;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

/* 文件展示区域样式 */
.file-display-container {
  margin: 16px 0;
}

.file-item {
  margin-bottom: 12px;
  padding: 12px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  transition: all 0.2s;
}

.file-item:hover {
  background: #e9ecef;
  border-color: #409eff;
}

.file-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.file-info i {
  color: #409eff;
  font-size: 18px;
  margin-right: 8px;
}

.file-name {
  flex: 1;
  color: #333;
  font-size: 14px;
  margin-right: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-actions {
  display: flex;
  gap: 8px;
}

.file-actions .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

/* 项目总金额显示区域样式 */
.amount-display-section {
  background: transparent;
  border: none;
  padding: 0;
  margin: 0 0 20px 0;
  display: flex;
  align-items: center;
}

.amount-display-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  margin-right: 8px;
}

.amount-display-content {
  display: flex;
  align-items: center;
}

.amount-loading {
  color: #409eff;
  font-size: 14px;
}

.amount-value {
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
}

.amount-unit {
  color: #909399;
  font-size: 14px;
  margin-left: 4px;
}
</style>
